<template>
  <div class="dashboard-container">
    <div class="container">
      <!-- 搜索栏 -->
      <div class="tableBar">
        <el-form :inline="true" @submit.prevent="handleSearch">
          <el-form-item label="菜品名称：">
            <el-input v-model="searchForm.name" placeholder="请填写菜品名称" clearable @clear="handleSearch" />
          </el-form-item>
          <el-form-item label="菜品分类：">
            <el-select v-model="searchForm.categoryId" placeholder="请选择" clearable>
              <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="售卖状态：">
            <el-select v-model="searchForm.status" placeholder="请选择" clearable>
              <el-option label="启售" :value="1" />
              <el-option label="停售" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="search-btn" @click="handleSearch" :loading="loading">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="tableLab">
          <el-button type="primary" @click="addDish()">+ 新建菜品</el-button>
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" stripe class="tableBox" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="菜品名称" />
        <el-table-column prop="image" label="图片">
          <template #default="{ row }">
            <el-image style="width: 80px; height: 40px;" :src="row.image" fit="contain">
              <template #error>
                <div class="image-slot">
                  <img src="@/assets/noImg.png" style="width: auto; height: 40px;" />
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="菜品分类" />
        <el-table-column prop="price" label="售价">
          <template #default="{ row }">
            <span>￥{{ row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售卖状态">
          <template #default="{ row }">
            <div class="tableColumn-status" :class="{ 'stop-use': row.status === 0 }">
              {{ row.status === 0 ? '停售' : '启售' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" min-width="150" />
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" class="blueBug" @click="addDish(row.id)">修改</el-button>
            <el-button type="text" size="small" class="delBut" @click="handleDelete(row.id)">删除</el-button>
            <el-button type="text" size="small" :class="row.status === 0 ? 'blueBug' : 'delBut'" @click="handleStatusChange(row)">
              {{ row.status === 0 ? '启售' : '停售' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pageList"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        @current-change="fetchData"
        @size-change="fetchData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getDishPage, deleteDish, updateDishStatus
} from '@/api/dish';
import { getCategoryList } from '@/api/category';
import type { IDish, IDishPageQuery } from '@/types/dish';
import type { ICategory } from '@/types/category';
import Empty from '@/components/Empty/index.vue';

// --- State ---
const router = useRouter();
const loading = ref(false);
const searchForm = reactive({ name: '', categoryId: undefined, status: undefined });
const tableData = ref<IDish[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const categoryList = ref<ICategory[]>([]);
const selectedIds = ref<number[]>([]);

// --- Core Methods ---
const fetchData = async () => {
  loading.value = true;
  try {
    const params: IDishPageQuery = {
      page: page.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      categoryId: searchForm.categoryId,
      status: searchForm.status,
    };
    const response = await getDishPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } finally {
    loading.value = false;
  }
};

const fetchCategoryList = async () => {
  try {
    const response = await getCategoryList({ type: 1 }); // type 1 for dish

    // 关键修改：使用 .map() 确保每个 item.id 都是 number 类型
    if (response && response.data) {
      categoryList.value = response.data.map(item => ({
        ...item,
        id: Number(item.id) // 强制转换为 number
      }));
    } else {
      categoryList.value = [];
    }

  } catch (error) {
    console.error("获取菜品分类失败:", error);
    categoryList.value = []; // 出错时清空列表
  }
};

const handleSearch = () => {
  page.value = 1;
  fetchData();
};

// --- Actions ---
const addDish = (id?: number) => {
  if (id) {
    router.push({ name: 'DishEdit', params: { id } });
  } else {
    router.push({ name: 'DishAdd' });
  }
};

const handleDelete = (id: number) => {
  // --- 核心修改在这里 ---
  // 1. 在调用确认框之前，先从 tableData 中找到这一行的数据
  const dishToDelete = tableData.value.find(item => item.id === id);

  // 2. 检查菜品是否存在且状态是否为“启售中” (status === 1)
  if (dishToDelete && dishToDelete.status === 1) {
    // 3. 如果是启售中，直接弹出错误提示并终止函数
    ElMessage.error('起售中的菜品不能删除');
    return;
  }

  // 4. 如果不是启售中，才继续执行原来的删除确认逻辑
  ElMessageBox.confirm('确认删除该菜品, 是否继续?', '提示', { type: 'warning' }).then(async () => {
    await deleteDish(String(id));
    ElMessage.success('删除成功！');
    fetchData();
  });
};

const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    return ElMessage.error('请选择要删除的菜品');
  }

  // --- 核心修改在这里 ---
  // 1. 检查选中的菜品中，是否有任何一个是“启售中”的
  const hasSoldItem = tableData.value.some(item =>
    selectedIds.value.includes(item.id) && item.status === 1
  );

  // 2. 如果有，则弹出错误提示并终止
  if (hasSoldItem) {
    ElMessage.error('选中的菜品中包含起售中的菜品，不能删除');
    return;
  }

  // 3. 如果全部都是“停售中”，才继续执行删除逻辑
  ElMessageBox.confirm('确认批量删除选中的菜品?', '提示', { type: 'warning' }).then(async () => {
    await deleteDish(selectedIds.value.join(','));
    ElMessage.success('批量删除成功！');
    fetchData();
  });
};

const handleStatusChange = (row: IDish) => {
  const newStatus = row.status === 0 ? 1 : 0;
  ElMessageBox.confirm(`确认更改该菜品状态为"${newStatus === 1 ? '启售' : '停售'}"?`, '提示', { type: 'warning' }).then(async () => {
    await updateDishStatus({ id: row.id, status: newStatus });
    ElMessage.success('菜品状态更改成功！');
    fetchData();
  });
};

const handleSelectionChange = (selection: IDish[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// --- Lifecycle Hook ---
onMounted(() => {
  fetchData();
  fetchCategoryList();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
}
.container {
  background: #fff;
  padding: 30px 28px;
  border-radius: 4px;
}
.tableBar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.tableLab {
  display: flex;
  align-items: center;
}
.tableBox {
  width: 100%;
}
.pageList {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
.tableColumn-status {
  &.stop-use { color: #f56c6c; }
}
.blueBug { color: #3370ff; }
.delBut { color: #f56c6c; }
</style>
